
package com.wang.myblog.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.wang.myblog.common.Constants;;
import com.wang.myblog.common.ResponseResult;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/admin")
public class UploadController {

    @Autowired
    private StandardServletMultipartResolver standardServletMultipartResolver;


    /**
     * markdown编辑器里面的图片
     * @param image
     * @return
     */
    @RequestMapping("/image/upload")
    @ResponseBody
    // 注意RequestParam中的name，不可改。
    public JSONObject imageUpload(@RequestParam("editormd-image-file") MultipartFile image) {
        JSONObject jsonObject = new JSONObject();
        if (image != null) {
//        String path = FileUtils.uploadFile(image);
            String path=null;
            String originFileName = image.getOriginalFilename();
            // 我们通过UUID 来重新重组文件名
            String uid = UUID.randomUUID().toString();
            assert originFileName != null;
            String suffix = originFileName.substring(originFileName.lastIndexOf('.') + 1);
            String path1 = Constants.FILE_UPLOAD_DIC + uid + "." + suffix;
            String returnPath = "/upload/" + uid + "." + suffix;//这里的upload对于config里面设置的路径回显，如果不一致没法实时看图片粘贴结果。
            File newFile = new File(path1);
            try {
                image.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            path=returnPath;
            System.out.println(path);
            jsonObject.put("url", path);
            jsonObject.put("success", 1);
            jsonObject.put("message", "upload success!");
            return jsonObject;
        }
        jsonObject.put("success", 0);
        jsonObject.put("message", "upload error!");
        return jsonObject;
    }

    /**
     * 通用图片，包括文章封面
     * @param file
     * @return
     */
    @RequestMapping("/image/uploads")
    @ResponseBody
    public String upload(@RequestParam("image") MultipartFile file){
        ResponseResult result=new ResponseResult();
        if(file!=null){
            String originFileName = file.getOriginalFilename();
            //生成文件名称通用方法
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            Random r = new Random();
            StringBuilder tempName = new StringBuilder();
            tempName.append(sdf.format(new Date())).append(r.nextInt(100));
            String newFileName = tempName.toString();
            String suffix = originFileName.substring(originFileName.lastIndexOf('.') + 1);
            String path1 = Constants.COMMON_IMAGE_DIC + newFileName + "." + suffix;
            String returnPath = "/uploads/" + newFileName + "." + suffix;//这里的upload对于config里面设置的路径回显，如果不一致没法实时看图片粘贴结果。
            File newFile = new File(path1);
            try {
               file.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            result.setCode(200);
            result.setData(returnPath);
            System.out.println(returnPath);

            return JSONObject.toJSONString(result);
        }
        result.setCode(500);
        result.setSuccess(0);
        result.setMessage("错误");
        return JSONObject.toJSONString(result);
    }

    public static boolean deleteCommonImg(String img){
        String fileName=img.substring(9);
        boolean flag=false;
        String filePath=Constants.COMMON_IMAGE_DIC+fileName;
        File file=new File(filePath);
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
}
